<template>
  <view class="department">
    <u--input
      v-model="department" border="none" placeholder="请选择部门" suffix-icon="search" readonly
      @click="show" />
    <tree-select-popup
      ref="tree" :list="listData" :fold-all="true" range-key="name" select-parent @confirm="confirm"
      @cancel="cancel" />
  </view>
</template>

<script>
import { getOrganization, fetchOrganizationList } from '@/api/system/organization'
import TreeSelectPopup from '@/components/TreeSelect/treeSelectPopup.vue'
export default {
  name: 'SystemOrganization',
  components: {
    TreeSelectPopup
  },
  props: {
    modelValue: {
      type: String,
      default: undefined
    },
    label: {
      type: String,
      default: '所属机构'
    },
    rules: {
      type: Array,
      default: function() {
        return []
      }
    },
    width: {
      type: String,
      default: '100%'
    },
    placeholder: {
      type: String,
      default: '请选择. . .'
    },
    headline: {
      type: String,
      default: '请选择目标'
    }
  },
  data() {
    return {
      listData: [],
      department: ''
    }
  },
  watch: {
    modelValue: {
      immediate: true,
      handler() {
        this.getOrganizationInfo()
      }
    }
  },
  created() {
    this.getBranch()
  },
  methods: {
    getOrganizationInfo() {
      this.department = undefined
      if (this.isNull(this.modelValue)) {
        return
      }
      getOrganization(this.modelValue).then((response) => {
        this.department = response.data.data.name
      })
    },
    getBranch() {
      fetchOrganizationList().then(response => {
        this.listData = response.data.data
        if (this.modelValue) {
          console.log(this.modelValue)
          this.Fullselect2(this.listData, this.modelValue)
        }
      })
    },
    // 部门
    show() {
      this.$refs.tree.show(this.modelValue)
    },
    // 确定回调事件
    confirm(e) {
      this.department = e[0].name
      this.$emit('update:modelValue', e[0].id)
    },
    // 取消回调事件
    cancel(e) {
      this.$refs.tree.hide()
    },
    // 递归回显已选择的部门
    Fullselect2(data, namedata) {
      if ((!data || data.length === 0) || (!namedata || namedata.length === 0)) {
        return
      }
      data.forEach(item => {
        this.Fullselect2(item.children, namedata)
        if (item.children && item.children.length > 0) {
          item.children.forEach(j => {
            if (namedata === j.id) {
              j.checked = true
            }
          })
        } else if (item.children.length === 0) {
          if (namedata === item.id) {
            item.checked = true
          }
        }
      })
    }
  }
}
</script>

<style lang="scss">
  .department {
    width: 100%;
  }
</style>
